<?php
/**
 * 管理员类
 * Created by PhpStorm.
 * User: zhangbing
 * Date: 2018/7/20
 * Time: 15:45
 */
namespace app\admin\controller;

class Admin extends Base{
    protected function _initialize(){
        if (in_array($this->request->action(),['adminshow','portraitupload','setpassword'])) {  //字母小写
            $this->needAuth  = false;  // 关闭权限验证
        }
        parent::_initialize();
    }
    /**
     * 列表
     * search 参数 $this->params:表单参数 input精确查找 时间查找 select状态查找
     * @return \think\response\View
     */
    public function adminList(){
        $search = search($this->params, ['a.username']);
        $where  = $search['where'] ? $search['where'].' and ' : '';
        $where .= 'a.id > '.\Param::GROUP_ADMIN.' and a.status in ('.\Param::STATUS_ON.', '.\Param::STATUS_OFF.')';
        $list   = $this->admin
            ->alias('a')
            ->field('a.*,c.pid,c.group_name')
            ->join([['auth_group_access b','a.id = b.uid','left'],['auth_group c','b.group_id = c.id','left']])
            ->where($where)
            ->paginate(10, false, ['query'=>$this->params, 'var_page'=>'page'])
            ->each(function($item, $key){
                if ($item['pid'] > 0) {
                    $group_name = $this->getValue($this->auth_group, ['id'=>$item['pid']], 'group_name');
                    $item['group_name'] = $group_name.' - '.$item['group_name'];
                }
                return $item;
            });
        return view('adminList',['list'=>$list,'params'=>$search['params']]);
    }

    /**
     * 操作
     * @return array|\think\response\View
     */
    public function adminSave(){
        if(IS_POST){
            try{
                if (!empty($this->params['id'])) {
                    //todo 更新
                    $group_info = $this->getRow($this->auth_group, $this->params['group_id']);

                    $row = $this->auth_group_access->where(['uid'=>$this->params['id']])->update(['group_id'=>$this->params['group_id']]);
                    if (false === $row) throw new \Exception('操作失败', -1);

                    $row = $this->admin->where(['id'=>$this->params['id']])->update(['update_time'=>time()]);
                    if (false === $row) throw new \Exception('操作失败', -1);

                    $this->logs[] = ['修改管理员', \Param::LOG_TYPE_EDIT, "修改“ID：{$this->params['id']}”管理员“{$this->params['username']}”，用户组为“{$group_info['group_name']}”"];
                } else {
                    //todo 添加
                    $validate = self::validate($this->params, 'Admin.adminAdd');  // 场景验证
                    if(true !== $validate) throw new \Exception($validate, -1);

                    $add = [
                        'username'    => $this->params['username'],
                        'password'    => password_hash($this->params['password'],true),
                        'create_time' => time()
                    ];
                    $uid = $this->admin->insertGetId($add);  // 添加管理员
                    $aid = $this->auth_group_access->insert(['uid'=>$uid, 'group_id'=>$this->params['group_id']]);  // 关系表添加记录
                    if (!$uid || false === $aid) throw new \Exception('操作失败', -1);

                    $this->logs[] = ['新增管理员', \Param::LOG_TYPE_ADD, "新增“ID：{$uid}”管理员“{$this->params['username']}”"];
                }
            } catch(\Exception $e) {
                return _error($e->getCode(),$e->getMessage());
            }
            logs($this->logs);  // 添加操作日志
            return _success();
        }

        if (!empty($this->params['source']) && $this->id != \Param::GROUP_ADMIN) {
            // 个人中心过来的，并且不是超管
            $group_id = $this->getValue($this->auth_group_access, ['uid'=>$this->id], 'group_id');
            $group = $this->getList($this->auth_group, ['pid'=>$group_id,'status'=>\Param::STATUS_ON]);  // 获取该用户下级用户组信息
        } else {
            // 管理员列表过来的
            $group = $this->getList($this->auth_group, ['id'=>['>',\Param::GROUP_ADMIN],'status'=>\Param::STATUS_ON]);  // 获取用户组信息
            $group = infinite($group);
        }

        if (!empty($this->params['id'])) {
            //todo 更新
            $html = 'adminSave';
            $info = $this->joinOne($this->admin,
                [['auth_group_access b','a.id = b.uid','inner']],
                'a.id = '.$this->params['id'],
                'a.id,a.username,b.group_id');
        } else {
            //todo 添加
            $html = 'adminAdd';
            $info = ['id'=> '','username'=>'','group_id'=>'','pid'=>''];
        }
        return view($html,['group'=>$group,'info'=>$info]);
    }

    /**
     * 修改密码
     * @return array|\think\response\View
     */
    public function setPassword(){
        $info = $this->getRow($this->admin, $this->params['id']);
        if(IS_POST){
            try{
                if (!$info || $info['status'] == \Param::STATUS_DEL) throw new \Exception('该用户不存在', -1);

                $check = password_verify($this->params['oldpassword'], $info['password']);
                if (!$check) throw new \Exception('密码错误', -1);

                $password = password_hash($this->params['password'], true);
                $row = $this->admin->update(['id'=>$this->params['id'],'password'=>$password,'update_time'=>time()]);
                if (false === $row) throw new \Exception('操作失败', -1);

                $this->logs[] = ['修改密码', \Param::LOG_TYPE_EDIT, "修改“ID：{$info['id']}”管理员“{$info['username']}”密码"];
            } catch(\Exception $e) {
                return _error($e->getCode(),$e->getMessage());
            }
            logs($this->logs);  // 添加操作日志
            return _success();
        }
        return view('setPassword',['info'=>$info]);
    }

    /**
     * 重置密码
     * 密码为123456
     * @throws \Exception
     */
    public function resetPassword(){
        if(IS_POST) {
            try {
                $info = $this->getRow($this->admin, $this->params['id']);
                if (!$info || $info['status'] == \Param::STATUS_DEL) throw new \Exception('该用户不存在', -1);

                $password = password_hash('123456', true);
                $row = $this->admin->update(['id' => $this->params['id'], 'password' => $password, 'update_time' => time()]);
                if (false === $row) throw new \Exception('操作失败', -1);

                $this->logs[] = ['修改密码', \Param::LOG_TYPE_EDIT, "重置“ID：{$info['id']}”管理员“{$info['username']}”密码"];
            } catch (\Exception $e) {
                return _error($e->getCode(), $e->getMessage());
            }
            logs($this->logs);  // 添加操作日志
            return _success();
        }
    }

    /**
     * 修改状态
     * @return array
     */
    public function status(){
        if(IS_POST){
            try{
                $info = $this->getRow($this->admin, $this->params['id']);
                if( !$info || $info['status'] == \Param::STATUS_DEL ) throw new \Exception('该用户不存在', -1);

                $row = $this->admin->update(['id'=>$this->params['id'],'status'=>$this->params['status'],'update_time'=>time()]);
                if (false === $row) throw new \Exception('操作失败', -1);

                $status = $this->params['status'] == \Param::STATUS_ON ? '已启用' : '已禁用';

                $this->logs[] = ['修改管理员', \Param::LOG_TYPE_EDIT, "修改“ID：{$info['id']}”管理员“{$info['username']}”状态为“{$status}”"];
            } catch(\Exception $e) {
                return _error($e->getCode(),$e->getMessage());
            }
            logs($this->logs);  // 添加操作日志
            return _success();
        }
    }

    /**
     * 详情
     * @return string|\think\response\Json|\think\response\View
     */
    public function adminShow(){
        //var_dump($this->params);
        //获取用户信息
        $info = $this->joinOne($this->admin,
            [['auth_group_access b','a.id = b.uid','inner'],['auth_group c','b.group_id = c.id','inner']],
            ['a.id'=>$this->params['id']],
            'a.*,b.group_id,c.pid,c.group_name'
        );

        // 获取日志列表
        $list = $this->admin_log
            ->where(['uid'=>$this->params['id']])
            ->order('id desc')
            ->paginate(10, false, ['query'=>$this->params, 'var_page'=>'page']);

        $group = [];
        $admin = [];
        if ($info['pid'] == 0) {
            // 获取下级用户组列表
            $group_where =
                $this->id == \Param::GROUP_ADMIN
                ? ['status'=>['in',[\Param::STATUS_ON,\Param::STATUS_OFF]],'id'=>['>',\Param::GROUP_ADMIN]]
                : ['pid'=>$info['group_id'],'status'=>['in',[\Param::STATUS_ON,\Param::STATUS_OFF]]];
            $group = $this->auth_group
                ->where($group_where)
                ->select();
            foreach ($group as $k=>$v) {
                $rules = $this->getColumn($this->auth_rule, ['id'=>['in',$v['auth_ids']]],'rule_name');
                $group[$k]['auth_ids'] = implode(',',$rules);
            }
            $info['count_group'] = count($group);


            // 获取下级用户列表
            $ids = array_column($group, 'id');
            $admin_where = $this->id == \Param::GROUP_ADMIN
                ? ['b.status'=>['neq',\Param::STATUS_DEL],'a.uid'=>['>',\Param::GROUP_ADMIN]]
                : ['b.status'=>['neq',\Param::STATUS_DEL],'a.uid'=>['in',$ids]];
            $admin = $this->auth_group_access
                ->alias('a')
                ->field('b.*,c.group_name')
                ->join([['admin b','a.uid = b.id','inner'],['auth_group c','a.group_id = c.id','inner']])
                ->where($admin_where)
                ->select();
            $info['count_admin'] = count($admin);
        } else {
            //非顶级用户组，拼接顶级组名
            $group_name = $this->getValue($this->auth_group, ['id'=>$info['pid']], 'group_name');
            $info['group_name'] = $info['group_name'].'-'.$group_name;
        }

        return view('adminShow',['list'=>$list,'info'=>$info,'group'=>$group,'admin'=>$admin]);
    }

    /**
     * 上传文件到服务器
     * @return string|\think\response\Json
     */
    public function portraitUpload(){
        if(IS_POST){
            try{
                $file = request()->file('image');
                $file_path = upload($file, $this->params['file_name']);

                $row = $this->admin->update(['id'=>$this->id,'portrait'=>$file_path[0],'update_time'=>time()]);
                if (false === $row) throw new \Exception('操作失败', -1);

                cookie('portrait', null);  // 记录头像
                cookie('portrait', $file_path[0]);

                $this->logs[] = ['修改管理员', \Param::LOG_TYPE_EDIT, "上传“ID：{$this->id}”管理员“{$this->info['username']}”头像"];
            } catch(\Exception $e) {
                return _error($e->getCode(),$e->getMessage());
            }
            logs($this->logs);  // 添加操作日志
            return _success(['path'=>$file_path[0]]);
        }
    }
}